from urllib import parse
import requests
import json

# 常量
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 " \
     "Safari/537.36 Edg/94.0.992.38 "


# 根据hash和album_id获取歌曲下载url
def getSongDownloadUrl(hash, album_id):
    # 请求头
    headers = {
        "User-Agent": UA
    }

    # 不知道干嘛用的参数
    # _ = 1497972864538

    # 请求参数
    params = {
        # "r": "play/getdata",
        "hash": hash,
        "album_id": album_id
        # "_": str(_)
    }

    # 请求歌曲页面
    # response = requests.get("https://www.kugou.com/yy/index.php?", headers=headers, params=params)
    response = requests.get(
        """https://www.kugou.com/yy/index.php?r=play/getdata&hash={hash}&album_id={albumid}&dfid=0Q0Clh1IcZaG3ey1J70RaTiL&mid=b6cf66837b18642cc269390b066649dc&platid=4""".
            format(hash=params["hash"],albumid=params["album_id"]), headers=headers)

    # 设置编码，防止乱码
    response.encoding = "utf-8"

    # 解析json
    data = json.loads(response.text)

    # 判断获取状态
    if int(data["status"]) == 0:
        print("歌曲下载地址获取失败")
        return None

    # 歌曲下载url
    playUrl = str(data["data"]["play_url"])
    return playUrl


# 下载歌曲
def download(url):
    return True


# 获取歌曲hash和album_id
def getSongsInfo(songName, whichPage: int, numOfSongs:int):

    # 请求头
    headers = {
        "User-Agent": UA
    }

    # 请求参数
    params = {
        "keyword": parse.quote(str(songName)),
        "page": str(whichPage)
    }

    # 搜索接口
    url = "http://songsearch.kugou.com/song_search_v2?page={page}&tag=em&platform=WebFilter&iscorrection=1&keyword={keyword}&pagesize={numOfSongs}&userid=-1&clientver=&filter=2&privilege_filter=0".format(page=params["page"], keyword=params["keyword"], numOfSongs=str(numOfSongs))

    # 获取json
    response = requests.get(url, headers=headers)
    response.encoding = "utf-8"

    # 解析json
    data = json.loads(response.text)

    # 检测是否获取成功
    if int(data["status"]) == 0:
        print("获取歌曲hash和album_id失败")
        return None

    # 初始化一个二维数组
    # 4 + 1的说明:
    # 4是留给hash, album_id, 歌手，歌曲名
    # 1是留给下载地址
    songsInfo = [["" for _ in range(4 + 1)] for __ in range(numOfSongs)]

    # 填充二维数组
    for i in range(0, numOfSongs):
        songsInfo[i][0] = data["data"]["lists"][i]["FileHash"]
        songsInfo[i][1] = data["data"]["lists"][i]["AlbumID"]
        songsInfo[i][2] = data["data"]["lists"][i]["SingerName"]
        songsInfo[i][3] = data["data"]["lists"][i]["SongName"]

    # print(songsInfo)
    return songsInfo
